<template>
  <div class="app-container">
    <h3>编辑课程</h3>
    <el-form v-loading="loading" ref="course" :rules="rules" :model="course" label-width="150px">
      <el-form-item label="课程名称" prop="courseName">
        <el-input v-model="course.courseName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="课程分类" prop="categoryId">
        <el-select v-model="course.categoryId" placeholder="请选择">
          <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.category" :value="item.categoryId" />
        </el-select>
      </el-form-item>
      <el-form-item label="课程图片" prop="courseImage">
        <pa-upload
          :action="action"
          :show-file-list="false"
          :file-list="fileList"
          :limit="1"
          :headers="headers"
          :on-success="uploadPicUrl"
          :on-remove="onRemove"
          list-type="picture-card"
          class="avatar-uploader"
          accept=".jpg, .jpeg, .png, .gif"
          tip="建议课程图尺寸:750*372" />
      </el-form-item>
      <el-form-item label="课程详情" prop="courseDesc">
        <vue-ueditor-wrap v-model="course.courseDesc" :config="ueditorConfig.config" @ready="ueditorConfig.ready" />
      </el-form-item>
      <el-form-item label="课程限制" prop="courseLimit">
        <el-radio-group v-model="course.courseLimit">
          <el-radio :label="1">免费</el-radio>
          <el-radio :label="2">会员免费</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="视频" prop="videoList">
        <div class="video-box">
          <div v-if="course.videoList.length>0" style="display:flex;">
            <!-- <video v-for="(item,index) in course.videoList" :key="index" :src="item.url" class="video"/> -->
            <div v-for="(item,index) in course.videoList" :key="index" class="video pos-r">
              <el-image :src="`${item.url}?vframe/jpg/offset/1`" fit="fill" style="width:100%;height:100%" />
              <div class="edit-btn">
                <el-button type="primary" plain @click="editVideo(item,index)">编辑</el-button>
              </div>
              <i class="el-icon-error delete del-btn" @click="delVideo(index)" />
            </div>
          </div>
          <div class="up-box" @click="uploadVideo">
            <i class="el-icon-plus plus" />
          </div>
        </div>
      </el-form-item>
      <div class="op-container">
        <el-button type="primary" @click="handlePublish('course')">提交</el-button>
        <el-button @click="handleCancel('course')">取消</el-button>
      </div>
    </el-form>

    <el-dialog :visible.sync="dialogFormVisible" :title="is_editVideo?'编辑视频':'新增视频'" width="500px">
      <el-form ref="dataForm" :rules="dataFormRules" :model="dataForm" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="视频文件" prop="url">
          <div class="upload-demo">
            <div class="el-upload el-upload--text txt-l" @click="handleClick" @keydown="handleKeydown">
              <el-button slot="trigger" size="small" type="primary" class="el-button el-button--primary el-button--small">选取文件</el-button>
              <input ref="input" type="file" name="file" class="el-upload__input" @change="handleChange">
              <div slot="tip" class="el-upload__tip">上传视频请提前压缩</div>
            </div>
          </div>
          <div v-if="dataForm.url" style="width: 145px;height: 145px;">
            <video-player ref="videoPlayer" :playsinline="true" :options="video_Config" class="video-player vjs-custom-skin" />
          </div>
        </el-form-item>
        <el-form-item label="视频标题" prop="resName">
          <el-input v-model="dataForm.resName" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="dataForm.sort" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <!-- v-if="dialogStatus=='create'" -->
        <el-button type="primary" @click="createData('dataForm')">确定</el-button>
        <!-- <el-button type="primary" @click="updateData">确定</el-button> -->
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" :show-close="false" :close-on-click-modal="false" title="视频模块" width="30%">
      <div class="progressContent">
        <el-progress v-if="!change_video_status" :percentage="videoPercentage" />
        <div v-if="!change_video_status" class="mt10">文件上传中</div>
        <div v-else class="mt10">服务器转码中...</div>
        <div class="mt10">请耐心等待</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
	.avatar-uploader .el-upload {
		width: 145px;
		height: 145px;
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #20a0ff;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		line-height: 120px;
		text-align: center;
	}

	.avatar {
		width: 145px;
		height: 145px;
		display: block;
	}

	.op-container {
		padding-left: 100px;
	}

	.up-box {
		width: 145px;
		height: 145px;
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		background-color: rgb(251, 253, 255);
		line-height: 143px;
		text-align: center;
	}

	.plus {
		font-size: 28px;
		color: rgb(140, 147, 157);
	}

	.video {
		width: 145px;
		height: 145px;
		border: 1px solid #d9d9d9;
		background-color: rgb(251, 253, 255);
		margin-right: 10px;
	}

	.video-box {
		display: flex;
	}

	.pos-r {
		position: relative;
	}

	.del-btn {
		font-size: 30px;
		position: absolute;
		right: -15px;
		top: -15px;
		color: #7e6a6a;
		z-index: 99;
		cursor: pointer;
	}

	.edit-btn {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}
</style>

<script>
import ueditorConfig from '@/config/ueditorConfig'
import {
  listCategory,
  saveCourse,
  getCourseDetail
} from '@/api/course'
import {
  listGoods
} from '@/api/goods'
import {
  createStorage
} from '@/api/storage'
import Editor from '@tinymce/tinymce-vue'
import {
  MessageBox
} from 'element-ui'
import {
  getToken
} from '@/utils/auth'
import upload from '@/components/Upload'
import videoConfig from '@/utils/videoConfig'
import uploadFun from '@/utils/qiniu'
import {
  getVideoToken,
  setVideoPfop,
  getVideoPfopStatus
} from '@/api/video'
export default {
  name: 'GoodsCreate',
  components: {
    Editor,
    'pa-upload': upload
  },

  data() {
    var validImg = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请上传图片'))
      } else {
        callback()
      }
    }
    var validVideo = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请上传图片'))
      } else {
        callback()
      }
    }
    return {
      is_editVideo: false,
      is_editVideo_index: null,
      fileList: [],
      ueditorConfig: ueditorConfig,
      action: `${process.env.BASE_API}/vms/v1/image/upload`,
      // 新加的数据
      loading: false,
      dialogFormVisible: false,
      course: {
        courseName: '',
        categoryId: '',
        courseDesc: '',
        courseImage: '',
        courseLimit: 1,
        // courseId: null,
        videoList: [],
        courseImageList: []
      },
      rules: {
        courseName: [{
          required: true,
          message: '商品名称不能为空',
          trigger: 'blur'
        }],
        categoryId: [{
          required: true,
          message: '请选择商品分类',
          trigger: 'change'
        }],
        courseDesc: [{
          required: true,
          message: '商品详情不能为空',
          trigger: 'blur'
        }],
        courseImage: [{
          required: true,
          validator: validImg,
          trigger: 'blur'
        }]
      },
      dataForm: {
        resName: '',
        sort: '',
        url: ''
      },
      dataFormRules: {
        resName: [{
          required: true,
          message: '视频标题不能为空',
          trigger: 'blur'
        }],
        sort: [{
          required: true,
          message: '排序不能为空',
          trigger: 'blur'
        }],
        url: [{
          required: true,
          validator: validVideo,
          trigger: 'blur'
        }]
      },
      categoryList: [],
      courseList: [],
      videoPercentage: 0,
      uploading_video: false, // 新增部分
      change_video_status: false,
      video_Config: videoConfig,
      show_video: true,
      timer: null,
      dialogVisible: false,

      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: [
          'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        ],
        toolbar: [
          'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
          'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
        ],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData)
            .then(res => {
              success(res.data.data.url)
            })
            .catch(() => {
              failure('上传失败，请重新上传')
            })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getCourseDetail()
    this.getCategory()
    this.getList()
  },
  mounted() {
    const self = this
    clearInterval(self.timer)
    if (!self.$store.state.video.videoToken) {
      getVideoToken().then(res => {
        self.$store.commit('SET_VIDEOTOKEN', res.data.data.token)
      })
    }
  },
  methods: {
    getCourseDetail() {
      const courseId = this.$route.query.id
      getCourseDetail({
        courseId: courseId
      }).then(res => {
        const data = res.data.data
        this.course = data
        this.fileList = [{
          url: data.courseImage
        }]
      })
    },
    // 文件
    handleClick() {
      this.$refs.input.value = ''
      this.$refs.input.click()
    },
    handleChange(ev) {
      const files = ev.target.files
      if (!files) return
      this.uploadFiles(files)
    },
    uploadFiles(files) {
      const self = this
      const observer = {
        next(res) {
          self.videoPercentage = parseInt(res.total.percent)
        },
        complete(res) {
          if (res.key) {
            setVideoPfop({
              key: res.key
            }).then(res => {
              self.change_video_status = true
              self.timer = setInterval(() => {
                getVideoPfopStatus({
                  id: res.data.data.persistentId
                }).then(res => {
                  res = res.data.data
                  if (res[0].status.code === 0) {
                    clearInterval(self.timer)
                    self.dialogVisible = false
                    self.change_video_status = false
                    self.video_Config[`sources`][0].src = res[0].url
                    self.dataForm.url = res[0].url
                  }
                })
              }, 1000)
            })
          }
        }
      }
      self.dialogVisible = true
      self.subscription = uploadFun(
        self.$store.state.video.videoToken,
        files[0],
        observer
      )
    },
    close() {
      const self = this
      self.change_video_show = false
      self.dialogVisible = false
      self.change_video_status = false
      if (self.subscription) {
        self.subscription.unsubscribe()
      }
      clearInterval(self.timer)
    },
    beforeDestroy() {
      clearInterval(self.timer)
    },
    handleKeydown(e) {
      if (e.target !== e.currentTarget) return
      if (e.keyCode === 13 || e.keyCode === 32) {
        this.handleClick()
      }
    },

    createData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.is_editVideo) {
            const data = Object.assign({}, this.dataForm)
            this.course.videoList.push(data)
            this.dialogFormVisible = false
          } else {
            console.log(this.dataForm, this.is_editVideo_index)
            this.course.videoList[this.is_editVideo_index] = Object.assign({},
              this.dataForm
            )
            console.log(this.course.videoList)
            this.dialogFormVisible = false
            this.is_editVideo = false
            this.is_editVideo_index = null
          }
        }
      })
      // this.is_editVideo = false
      // this.is_editVideo_index = null
    },
    getCategory() {
      listCategory({
        index: 0,
        size: 100
      })
        .then(response => {
          this.categoryList = response.data.data.content
        })
        .catch(() => {
          this.list = []
        })
    },
    getList() {
      listGoods({
        index: 1,
        size: 100
      })
        .then(response => {
          this.courseList = response.data.data.content
        })
        .catch(() => {
          this.list = []
        })
    },
    handleCancel: function(formName) {
      this.$refs[formName].resetFields()
    },
    handlePublish: function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loading = true
          const params = this.course
          saveCourse(params)
            .then(res => {
              this.loading = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
              this.$router.push({
                name: 'courseList'
              })
            })
            .catch(response => {
              this.loading = false
              MessageBox.alert('后台出错了', '警告', {
                confirmButtonText: '确定',
                type: 'error'
              })
            })
        } else {
          console.log(valid)
        }
      })
    },
    uploadPicUrl: function(response) {
      this.course.courseImage = response.data.fileUrl
    },
    onRemove(file, fileList) {
      this.fileList.forEach((item, index) => {
        if (file.url === item.url) {
          this.fileList.splice(index, 1)
          this.course.courseImage = ''
        }
      })
    },
    // uploadOverrun: function() {
    //   this.$message({
    //     type: 'error',
    //     message: '上传文件个数超出限制!最多上传5张图片!'
    //   })
    // },
    // handleGalleryUrl(response, file, fileList) {
    //   if (response.errno === 0) {
    //     this.goods.gallery.push(response.data.url)
    //   }
    // },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.goods.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.goods.gallery[i] === url) {
          this.goods.gallery.splice(i, 1)
        }
      }
    },
    uploadVideo() {
      this.dialogFormVisible = true
      this.dataForm.resName = ''
      this.dataForm.sort = ''
      this.dataForm.url = ''
    },
    getOption(url) {
      const tem = videoConfig
      tem[`sources`][0].src = url
      return tem
    },
    delVideo(index) {
      this.course.videoList.splice(index, 1)
    },
    editVideo(item, index) {
      this.is_editVideo = true
      this.is_editVideo_index = index
      this.dialogFormVisible = true
      this.dataForm.resName = item.resName
      this.dataForm.resId = item.resId
      this.dataForm.sort = item.sort
      this.dataForm.url = item.url
      this.video_Config[`sources`][0].src = item.url
    }
  }
}
</script>
